<script setup lang="ts">
import { message } from 'ant-design-vue'
import { ColumnHeightOutlined, DeleteOutlined, EditOutlined, PlayCircleOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { onMounted, ref } from 'vue'
import type { MenuProps, TableColumnsType, TableProps } from 'ant-design-vue'
import { startWithInput, workflowList } from '~@/api/flow/medatata'
import type { WorkflowListSearch } from '~@/api/flow/medatata'

defineOptions({
  name: 'FlowList',
})

const router = useRouter()

// 表格列
const columns: TableColumnsType = [
  {
    title: '序号',
    dataIndex: 'key',
    key: 'key',
    width: 80,
    align: 'center',
  },
  {
    title: '流程名',
    dataIndex: 'name',
    key: 'name',
    width: 300,
  },
  {
    title: '版本',
    dataIndex: 'version',
    key: 'version',
    width: 100,
    align: 'center',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200,
    align: 'center',
  },
]

const workflowInputVisible = ref(false)
const loading = ref(false)
const data = ref<any>([])
const searchParam = ref<WorkflowListSearch>({})

onMounted(() => {
  getData()
})

// 延时
function sleep(time: number) {
  return new Promise((resolve) => {
    setTimeout(resolve, time)
  })
}

// 表格数据加载
async function getData() {
  loading.value = true
  await sleep(800)
  try {
    const res = await workflowList(searchParam.value)
    data.value = res.data
  }
  catch (error) {
    message.error('获取数据失败')
  }
  finally {
    loading.value = false
  }
}

// 编辑
function editor(record: any) {
  router.push({ name: 'FlowEditor', query: { name: record.name, version: record.version } })
}

const formModel = reactive<any>({
  name: undefined,
  callNo: undefined,
  desc: undefined,
  status: undefined,
  updatedAt: undefined,
})

const workflowInputModel = reactive<any>({
  name: undefined,
  version: undefined,
  input: undefined,
})

const tableSize = ref<string[]>(['small'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])

function onSearch() {
  searchParam.value = { ...formModel }
  getData()
}

function onReset() {
  formModel.name = undefined
  formModel.callNo = undefined
  formModel.desc = undefined
  formModel.status = undefined
  formModel.updatedAt = undefined
  searchParam.value = {}
  getData()
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

function handleAdd() {
  router.push({ name: 'FlowEditor' })
}

function deleteWorkflow(record: any) {
  console.log(record)
  message.error('暂未实现')
}

const startLoading = ref(false)
function startWorkflowBtn(record: any) {
  workflowInputVisible.value = true
  workflowInputModel.name = record.name
  workflowInputModel.version = record.version
}
// 开始流程
function startWorkflowSubmit() {
  startLoading.value = true
  startWithInput(workflowInputModel).then((res) => {
    console.log(res)
    message.success('启动成功')
  }).finally(() => {
    workflowInputModel.name = undefined
    workflowInputModel.version = undefined
    workflowInputModel.input = undefined
    workflowInputVisible.value = false
    startLoading.value = false
  })
}
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 10 }" :model="formModel" layout="vertical">
        <a-row :gutter="[48, 0]" justify="space-between">
          <a-col :span="8">
            <a-form-item name="name" label="流程名称">
              <a-input v-model:value="formModel.name" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="desc" label="描述">
              <a-input v-model:value="formModel.desc" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="updatedAt" label="上次调用时间">
              <a-date-picker v-model:value="formModel.updatedAt" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :columns="columns" :data-source="data" :loading="loading" :size="tableSize[0] as TableProps['size']" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'key'">
            <span>
              {{ data.indexOf(record) + 1 }}
            </span>
          </template>
          <template v-if="column.key === 'action'">
            <span>
              <a-tooltip title="启动">
                <PlayCircleOutlined style="color: #52c41a" @click="startWorkflowBtn(record)" />
              </a-tooltip>
              <!-- <a-button type="link" style="color: #52c41a" size="small" :icon="h(PlayCircleOutlined)" @click="editor(record)">启动</a-button> -->
              <a-divider type="vertical" />
              <!-- <a-button type="link" size="small" @click="editor(record)">编辑</a-button> -->
              <a-tooltip title="编辑">
                <EditOutlined style="color: #1677ff" @click="editor(record)" />
              </a-tooltip>
              <a-divider type="vertical" />
              <a-popconfirm placement="bottom" title="确定删除吗？" ok-text="是" cancel-text="否" @confirm="deleteWorkflow(record)">
                <a-tooltip title="删除">
                  <DeleteOutlined style="color: #ff4d4f" />
                </a-tooltip>
                <!-- <a-button type="link" size="small" danger>删除</a-button> -->
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="workflowInputVisible" title="开始流程" destroy-on-close>
      <template #footer>
        <a-button key="back" @click="workflowInputVisible = false">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="startLoading" @click="startWorkflowSubmit">
          确定
        </a-button>
      </template>
      <a-form
        :model="workflowInputModel"
        name="basic"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        autocomplete="off"
      >
        <a-form-item
          label="流程名称"
          name="name"
        >
          <a-input v-model:value="workflowInputModel.name" disabled />
        </a-form-item>
        <a-form-item
          label="版本"
          name="version"
        >
          <a-input v-model:value="workflowInputModel.version" disabled />
        </a-form-item>
        <a-form-item
          label="入参"
          name="input"
        >
          <MonacoEditor v-model="workflowInputModel.input" language="json" />
        </a-form-item>
      </a-form>
    </a-modal>
  </page-container>
</template>
